package com.spera.genutil;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.model.BaseResult;

public class WechatUtil {
	
	/**
	 * 获取微信accesstoken
	 * @return
	 */
	public static String getAccessToken(){
		String access_token = "";
		Map<String, String> map = new HashMap<String, String>();
        map.put("corpid", BuzWechatContent.CORPID);
        map.put("corpsecret", BuzWechatContent.CORPSECRET);
		try {
			HttpClient client = HttpClientNUtils.getConnection();
	        HttpUriRequest get = HttpClientNUtils.getRequestMethod(map, "https://qyapi.weixin.qq.com/cgi-bin/gettoken", "get");
	        HttpResponse response = client.execute(get);
	        String content = "";
	        if (response.getStatusLine().getStatusCode() == 200) {
	            HttpEntity entity = response.getEntity();
	            content = EntityUtils.toString(entity, "utf-8");
	        } else {
	        	return "";
	        }
			
			Map<String, Object> mapParm = JSON.parseObject(content, new TypeReference<Map<String, Object>>(){});
			if(ApplicationUtils.isNotNull(mapParm.get("access_token"))){
				access_token = (String)mapParm.get("access_token");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return access_token;
	}
	
	/**
	 * 企业号推送内容
	 * @param access_token
	 * @param sb
	 * @return
	 */
	public static BaseResult sendQyhNotice(String access_token,String users,String content){
		BaseResult ret = new BaseResult();
		if(!ApplicationUtils.isNotNull(access_token)){
			ret.setStatus("0");
			ret.setMsg("token不可为空");
			return ret;
		}
		String nUrl = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token;
		try{
			StringBuffer sb = new StringBuffer();
			sb.append("{\"touser\":\""+users.replaceAll(",", "|")+"\",");
			sb.append("\"msgtype\":\"text\",");
			sb.append("\"agentid\":\"4\",");
			sb.append("\"text\":{\"content\":\""+content+"\"},");
			sb.append("\"safe\":\"0\"}");
			String retContent = HttpClientNUtils.httpPost(nUrl, sb.toString());
			Map<String, Object> mapParm = JSON.parseObject(retContent, new TypeReference<Map<String, Object>>(){});
			ret.setDataset(mapParm);
		}catch(Exception e){
			e.printStackTrace();
			ret.setStatus("0");
			ret.setMsg("发送失败");
		}
		return ret;
	}
}
